package com.yimi.yinhepda.views.dispatch_module;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.BuildScanByHandAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.DispactchScanMasterTableDao;
import com.yimi.yinhepda.db.dao.DispactchScanTableDao;
import com.yimi.yinhepda.db.table.DispatchScanMasterTable;
import com.yimi.yinhepda.db.table.DispatchScanTable;
import com.yimi.yinhepda.entity.bean.AddEntity;
import com.yimi.yinhepda.entity.bean.DispatchEntity;
import com.yimi.yinhepda.entity.response.CheckWayBillNoStatus;
import com.yimi.yinhepda.entity.response.CheckWayBillNoStatusResponse;
import com.yimi.yinhepda.entity.response.DispatchScanResponse;
import com.yimi.yinhepda.entity.response.QueryWaybillByChildNoResponse;
import com.yimi.yinhepda.entity.response.WaybillInfo;
import com.yimi.yinhepda.event.CountEvent;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.IntentUtils;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.base.BaseInitActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;

import static java.util.Collections.sort;

/**
 * @author 000432
 * @date 2017/4/22 0022
 *
 * 配送手动添加
 */

public class DispatchAddByHandActivity extends BaseInitActivity {
  /** 标题栏左边 */
  @Bind(R.id.title) TextView mTvTitle;
  /** 标题栏中间 */
  @Bind(R.id.num) TextView mTvNum;
  /** 添加按钮 */
  @Bind(R.id.manual_add_btn) Button mBtnAdd;
  /** 条码输入框 */
  @Bind(R.id.load_addchildwaybill_ed) EditText mEtBarcode;
  @Bind(R.id.add_chidlwaybill_listview) ListView mListView;
  @Bind(R.id.manaul_add_count) TextView mTvAddTip;
  @Bind(R.id.add_childwaybill_back) ImageView mImgAddBack;
  @Bind(R.id.add_childwaybill_ok) ImageView mImgAddOk;

  private DispactchScanTableDao mDispactchScanTableDao;
  private DispactchScanMasterTableDao dispactchScanMasterTableDao;
  private List<AddEntity> mAddEntityList = new ArrayList<>();
  private BuildScanByHandAdapter mAdapter;
  /** 手加票 */
  private int mHandAddBill;
  /** 手加件 */
  private int mHandAdditem;
  /** 目的地 */
  private String destCode;
  private String destName;
  /** 总的未上传数量 */
  private int totalNotUploadNum;
  private String mTaskNo;

  /** 派送任务集合 */
  private List<DispatchEntity> mDispatchDataList;

  @Override public String getPageName() {
    return getString(R.string.page_dispatch_addbyhand);
  }

  public DispatchAddByHandActivity() {
    super(true);
  }

  /**
   * 扫描的回调
   */
  @Override protected void handleBarCode(String result) {
    super.handleBarCode(result);
    if (result == null) {
      SoundVibratorManager.playSound(2);
      showToast("运单号扫描失败");
    } else {
      mEtBarcode.setText(result);
    }
  }

  @Override public int getContentViewId() {
    return R.layout.activity_add_childbillway;
  }

  @Override public void initView(Bundle savedInstanceState) {
    EventBus.getDefault().register(this);
    mTvTitle.setText(getString(R.string.hand_add_title));
  }

  @Override public void initEvent() {
    mBtnAdd.setOnClickListener(this);
    mImgAddBack.setOnClickListener(this);
    mImgAddOk.setOnClickListener(this);
  }

  @Override public void initData() {
    //目的地
    destCode = getIntent().getStringExtra(IntentUtils.BUILD_DEST);
    destName = getIntent().getStringExtra(IntentUtils.BUILD_DEST_NAME);
    mTaskNo = getIntent().getStringExtra("taskno");

    mDispatchDataList = DispatchScanActivity.mDispatchDataList;

    //数据库对象
    mDispactchScanTableDao = new DispactchScanTableDao();
    dispactchScanMasterTableDao = new DispactchScanMasterTableDao();
    /** 查询未上传数据*/
    totalNotUploadNum = mDispactchScanTableDao.queryNotUploadDataNum();
    mTvNum.setText(totalNotUploadNum + "");

    //列表
    mAdapter = new BuildScanByHandAdapter(this, mAddEntityList);
    mListView.setAdapter(mAdapter);
  }

  @Override public void onClick(View v) {
    super.onClick(v);
    switch (v.getId()) {
      case R.id.manual_add_btn:
        //添加按钮
        startAddBarData();
        break;
      case R.id.add_childwaybill_back:
        //返回按钮
        activityBackMethod();
        break;
      case R.id.add_childwaybill_ok:
        //确定按钮
        activityBackMethod();
        break;
      default:
        break;
    }
  }

  /**
   * 开始添加条码的操作
   */
  private void startAddBarData() {

    final String barCodeStr = mEtBarcode.getText().toString().trim();
    if (!StringUtils.isWaybillNo(barCodeStr)) {
      showToast("运单号不规范!");
      SoundVibratorManager.playSound(2);
      return;
    }

    /***
     * buildList 是扫描页面全局的
     */
    if (mDispatchDataList == null) {
      return;
    }
    for (int i = 0; i < mDispatchDataList.size(); i++) {
      //当前行的运单信息，包括子单的集合
      DispatchEntity currentItemInfo = mDispatchDataList.get(i);
      /** 判断子单是不是以主单开始的,减少循环次数*/
      if (!barCodeStr.startsWith(String.valueOf(currentItemInfo.getWaybillNo()))) {
        continue;
      }
      //子单的集合
      List<DispatchScanResponse.DispatchWaybillChild> childList = currentItemInfo.getChildList();
      //循环子单的集合
      if (childList != null) {
        for (DispatchScanResponse.DispatchWaybillChild child : childList) {
          //子单字符串
          String childWaybillno = child.getChildNo();
          //扫描子单和集合中一个子单相同
          if (barCodeStr.equals(childWaybillno)) {
            Integer flag = child.getFlag();
            if (flag == 1) {
              SoundVibratorManager.playSound(2);
              showToast("重复扫描!");
            } else {
              /** 扫描数据插入到表中*/
              if (insertScannedData(null, currentItemInfo, childWaybillno, "1") < 0) {
                SoundVibratorManager.playSound(2);
                showToast("插入数据库失败!");
                return;
              }

              totalNotUploadNum++;
              mTvNum.setText(totalNotUploadNum + "");
              EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

              /** 设置该子单为已扫描的状态*/
              child.setFlag(1);
              SoundVibratorManager.playSound(1);

              /** 添加到列表*/
              AddEntity addEntity = new AddEntity();
              addEntity.setWaybillNum(currentItemInfo.getWaybillNo() + "");
              addEntity.setChildwayBillNum(child.getChildNo());
              mAddEntityList.add(addEntity);
              mAdapter.notifyDataSetChanged();

              /** 刷新手动添加票和件*/
              mHandAddBill = getHandAddBill();
              mHandAdditem++;
              mTvAddTip.setText(String.format(getString(R.string.hand_add_num), mHandAddBill, mHandAdditem));
            }

            /** 更新当前行到第一行*/
            mDispatchDataList.remove(i);
            mDispatchDataList.add(0, currentItemInfo);
            return;
          }
        }
      }
    }

    showToast(getString(R.string.num_no_in_task_list));
    SoundVibratorManager.playSound(2);
    //强扫 该条码不在配送任务内，子单下载主单
    //MyDialog dialog = new MyDialog(DispatchAddByHandActivity.this);
    //dialog.setIcon(R.drawable.alert);
    //dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
    //dialog.setTitle("系统提示");
    //dialog.setMessage("不在该任务下的运单，是否继续？");
    //dialog.setPositiveClickListener(R.drawable.btn_login_selector, "是", new DialogInterface.OnClickListener() {
    //  @Override public void onClick(DialogInterface dialog, int which) {
    //    dialog.dismiss();
    //    //调用接口，校验该运单是否已经预约，没有预约给出相应提示
    //    checkWaybillNoStatus(barCodeStr);
    //  }
    //});
    //dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", new DialogInterface.OnClickListener() {
    //  @Override public void onClick(DialogInterface dialog, int which) {
    //    dialog.dismiss();
    //  }
    //});
    //dialog.show();
  }

  /**
   * 校验运单状态
   */
  private void checkWaybillNoStatus(String result) {
    final String tempResult = result;
    if (result.length() > 12) {
      result = result.substring(0, 12);
    } else if (result.length() != 12) {
      showToast("运单号不规范!");
      SoundVibratorManager.playSound(2);
      return;
    }
    setScannerEnabled(false);
    showPgDlg("正在校验运单...");
    Map param = new HashMap();
    param.put("waybillNo", result);
    param.put("destZoneCode", destCode);
    final String finalResult = result;
    new NetRequest().setMethod(NetRequest.Method.GET)
        .setUrl(Constants.URL_CHECK_ORDER_WAYBILLNO)
        .setParams(param)
        .setResponsClazz(CheckWayBillNoStatusResponse.class)
        .execute(new UICallBack() {
          @Override public void onError(String msg) {
            setScannerEnabled(true);
            dismissPgDlg();
            SoundVibratorManager.playSound(2);
            showToast(msg);
          }

          @Override public void onSuccess(Object obj) {
            setScannerEnabled(true);
            dismissPgDlg();
            if (obj instanceof CheckWayBillNoStatusResponse) {
              final String subResult = "非今日运单";
              String resultStr = "";
              CheckWayBillNoStatusResponse response = (CheckWayBillNoStatusResponse) obj;
              List<CheckWayBillNoStatus> lists = response.getData();
              if (lists != null && lists.size() > 0) {
                CheckWayBillNoStatus entity = lists.get(0);
                if (entity.getIsDelete() == 1) {
                  resultStr = "该运单已删除！";
                } else if (entity.getWaybillFlag() != 0) {
                  if (entity.getWaybillFlag() == 1) {
                    resultStr = "该运单已中止！";
                  } else if (entity.getWaybillFlag() == 2) {
                    resultStr = "该运单已作废！";
                  }
                } else if (entity.getDispatchStatus() == 1) {
                  resultStr = "该运单已派送未交款！";
                } else if (entity.getDispatchStatus() == 2) {
                  resultStr = "该运单已派送已交款！";
                } else if (entity.getOptionStatus() == 3) {
                  resultStr = "该运单已更改未审核！";
                } else if (entity.getSubscribeTime() == null || entity.getSubscribeTime().equals("")) {
                  resultStr = "该运单未预约！";
                } else if (entity.getSubscribeTimeStr() != null && !DispatchScanActivity.checkTodaySubscribeTime(entity.getSubscribeTimeStr())) {
                  resultStr = subResult;
                } else if (entity.getStoreTimeStr() == null
                    || entity.getStoreTimeStr().equals("")
                    || entity.getInventoryStatus() == 3
                    || entity.getInventoryStatus() == 4) {
                  resultStr = "该运单尚未入库！";
                }
              } else {
                resultStr = "未查询到该运单数据！";
              }
              if (resultStr.equals(subResult)) {
                //非今日运单,提示用户
                MyDialog dialog = new MyDialog(DispatchAddByHandActivity.this);
                dialog.setIcon(R.drawable.alert);
                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                dialog.setTitle("系统提示");
                dialog.setMessage("不是预约今日的运单，是否继续");
                dialog.setPositiveClickListener( "是", new DialogInterface.OnClickListener() {
                  @Override public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    downloadWaybillNo(tempResult);
                  }
                });
                dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", null);
                dialog.show();
                SoundVibratorManager.playSound(2);
              } else if (!resultStr.equals("")) {
                MyDialog dialog = new MyDialog(DispatchAddByHandActivity.this);
                dialog.setIcon(R.drawable.alert);
                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                dialog.setTitle("系统提示");
                dialog.setMessage(resultStr);
                dialog.setPositiveClickListener( "确定", new DialogInterface.OnClickListener() {
                  @Override public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                  }
                });
                dialog.show();
                SoundVibratorManager.playSound(2);
              } else {
                downloadWaybillNo(tempResult);
              }
            }
          }
        });
  }

  /**
   * 子单下载主单
   */
  private void downloadWaybillNo(final String result) {
    setScannerEnabled(false);
    showPgDlg("正在子单下载主单...");

    //扫描数据上传完后  调完成任务
    //QueryWaybillByChildNoRequest mQueryWaybillByChildNoRequest = new QueryWaybillByChildNoRequest();
    //mQueryWaybillByChildNoRequest.setChildWaybillNo(result);

    Map param = new HashMap();
    param.put("childWaybillNo", result);
    new NetRequest().setMethod(NetRequest.Method.GET)
        .setUrl(Constants.URL_FORCE_SCAN)
        .setParams(param)
        .setResponsClazz(QueryWaybillByChildNoResponse.class)
        .execute(new UICallBack() {
          @Override public void onError(String msg) {
            //开启扫描
            setScannerEnabled(true);
            dismissPgDlg();
            SoundVibratorManager.playSound(2);
            if (msg != null) {
              showToast("子单下载主单失败:" + msg);
            } else {
              showToast("子单下载主单失败!");
            }
          }

          @Override public void onSuccess(Object obj) {

            final QueryWaybillByChildNoResponse response = (QueryWaybillByChildNoResponse) obj;
            //合并数据到内存，并插入当前条码到数据库
            //路由验证
            if (!Common.waybillRouteWrong(response.getData().getRouteCode(), destCode)) {
              //合并数据到内存，并插入当前条码到数据库
              merge(response.getData(), result);
            } else {
              MyDialog dialog = new MyDialog(DispatchAddByHandActivity.this);
              dialog.setIcon(R.drawable.alert);
              dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
              dialog.setTitle("系统提示");
              dialog.setMessage("请核对正确目的站是否派送？");
              dialog.setPositiveClickListener( "确定", new DialogInterface.OnClickListener() {
                @Override public void onClick(DialogInterface dialog, int which) {
                  dialog.dismiss();
                  //合并数据到内存，并插入当前条码到数据库
                  merge(response.getData(), result);
                }
              });
              dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", new DialogInterface.OnClickListener() {
                @Override public void onClick(DialogInterface dialog, int which) {
                  dialog.dismiss();
                }
              });
              dialog.show();
            }
            //开启扫描
            setScannerEnabled(true);
            dismissPgDlg();
          }
        });
  }

  /**
   * 合并数据到内存，并插入当前条码到数据库
   */
  private void merge(WaybillInfo data, String result) {
    //构建数据
    DispatchEntity dispatchScanEntity = new DispatchEntity();
    dispatchScanEntity.setWaybillNo(data.getWaybillNo());
    dispatchScanEntity.setQuantity(data.getQuantity());
    dispatchScanEntity.setStoreQuantity(data.getNowInventory());
    dispatchScanEntity.setRealWeightQty(data.getRealWeight().doubleValue());
    dispatchScanEntity.setMeterageWeightQty(data.getChargeableWeight().doubleValue());
    dispatchScanEntity.setVolume(data.getVolume().doubleValue());

    List<DispatchScanResponse.DispatchWaybillChild> childList = new ArrayList<DispatchScanResponse.DispatchWaybillChild>();
    for (int i = 0; i < data.getQuantity(); i++) {
      String childWaybillNo = data.getWaybillNo() + String.format("%03d", i + 1);
      DispatchScanResponse.DispatchWaybillChild mChildInfo = new DispatchScanResponse.DispatchWaybillChild();
      if (result.equals(childWaybillNo)) {
        mChildInfo.setFlag(1);
      } else {
        mChildInfo.setFlag(0);
      }
      mChildInfo.setChildNo(childWaybillNo);
      childList.add(mChildInfo);
    }
    //子单集合加入到运单对象中
    dispatchScanEntity.setChildList(childList);

    //扫描的子单插入到数据库
    if (insertScannedData(data, dispatchScanEntity, result, "2") < 0) {
      SoundVibratorManager.playSound(2);
      showToast("插入数据失败!");
      return;
    }

    //未上传数据
    totalNotUploadNum++;
    mTvNum.setText(totalNotUploadNum + "");
    EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

    SoundVibratorManager.playSound(1);

    sort(mDispatchDataList);
    mDispatchDataList.add(0, dispatchScanEntity);

    /** 添加到列表*/
    AddEntity addEntity = new AddEntity();
    addEntity.setWaybillNum(dispatchScanEntity.getWaybillNo() + "");
    addEntity.setChildwayBillNum(result);
    mAddEntityList.add(addEntity);
    mAdapter.notifyDataSetChanged();

    /** 刷新手动添加票和件*/
    mHandAddBill = getHandAddBill();
    mHandAdditem++;
    mTvAddTip.setText(String.format(getString(R.string.hand_add_num), mHandAddBill, mHandAdditem));
  }

  /**
   * 插入已经扫描的数据到表中
   *
   * @param currentItemInfo 当前运单号的相关信息
   * @param waybillChildNo 当前子单的相关信息
   */
  private int insertScannedData(WaybillInfo data, DispatchEntity currentItemInfo, String waybillChildNo, String remark) {
    int result = 0;
    if (data != null) {
      //判断主单号不存在则插入主单号
      boolean exitWaybillNo = dispactchScanMasterTableDao.exitDataByWaybillNo(currentItemInfo.getWaybillNo(), mTaskNo);
      if (!exitWaybillNo) {
        try {
          DispatchScanMasterTable dispatchScanMasterTable = new DispatchScanMasterTable();
          dispatchScanMasterTable.setTaskNo(mTaskNo);
          dispatchScanMasterTable.setWaybillNo(data.getWaybillNo());
          dispatchScanMasterTable.setQuantity(data.getQuantity());
          dispatchScanMasterTable.setRealWeight(data.getRealWeight());
          dispatchScanMasterTable.setChargeableWeight(data.getChargeableWeight());
          dispatchScanMasterTable.setRouteCode(data.getRouteCode());
          dispatchScanMasterTable.setPackingSpecification(data.getPackingSpecification());
          dispatchScanMasterTable.setNowInventory(data.getNowInventory());
          dispatchScanMasterTable.setRemark(remark);
          dispactchScanMasterTableDao.insert(dispatchScanMasterTable);
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }

    boolean flag = mDispactchScanTableDao.exitDataByChildWaybillNo(waybillChildNo, mTaskNo);
    if (flag) {
      return result;
    }

    DispatchScanTable dispatchScanTable = new DispatchScanTable();
    dispatchScanTable.setTaskNo(mTaskNo);
    dispatchScanTable.setWaybillNo(currentItemInfo.getWaybillNo());
    dispatchScanTable.setChildNo(waybillChildNo);
    //标志：2-强扫，1-非强扫
    dispatchScanTable.setChildRemark(remark);
    dispatchScanTable.setDispatchArea(currentItemInfo.getDispatchAreaCode());
    //操作方式
    dispatchScanTable.setInputType(2);
    dispatchScanTable.setScanTime(Constants.GetScanTime());
    dispatchScanTable.setOperTime(Constants.GetSysTime());
    dispatchScanTable.setIsUpload(0);
    dispatchScanTable.setSacnDeptCode(SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE));
    dispatchScanTable.setScanEmpCode(SharedPreferUtil.getInstance().getValue(Common.COMP_CODE));
    dispatchScanTable.setUserIp("");
    dispatchScanTable.setTaskScanQuantity(currentItemInfo.getTaskScanQuantity());
    try {
      result = mDispactchScanTableDao.insert(dispatchScanTable);
    } catch (Exception e) {
      e.printStackTrace();
      result = -1;
    }
    return result;
  }

  /**
   * 手动添加的票数
   */
  private int getHandAddBill() {
    Set<String> set = new HashSet<String>();
    for (AddEntity item : mAddEntityList) {
      set.add(item.getWaybillNum());
    }
    return set.size();
  }

  @Subscribe(threadMode = ThreadMode.MAIN) public void onMainEventBus(CountEvent countEvent) {
    mTvNum.setText(countEvent.getCount() + "");
  }

  @Override protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
  }

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
      activityBackMethod();
    }
    return false;
  }

  private void activityBackMethod() {
    //Intent intent = new Intent();
    //intent.putExtra(IntentUtils.DISPATCH_LIST, (Serializable) mDispatchDataList);
    //setResult(RESULT_OK, intent);
    finish();
  }
}
